package com.hmkj.quartz.config;

import com.hmkj.boot.utils.SpringContextUtils;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.constant.State;
import com.hmkj.core.po.system.Configure;
import com.hmkj.core.po.system.MessageTemplate;
import com.hmkj.core.service.cache.RedisService;
import com.hmkj.core.service.system.ConfigureService;
import com.hmkj.core.service.system.MessageTemplateService;
import com.hmkj.quartz.queue.MessageQueueThread;
import com.hmkj.quartz.queue.OrderQueueThread;
import com.xiaoleilu.hutool.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 初始化数据
 */
@Slf4j
@Component
public class Init implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {

        ThreadUtil.execute(new MessageQueueThread());               // 短信、邮件、站内信等通知消息队列

        ThreadUtil.execute(new OrderQueueThread());               // 策略处理队列

        log.info("初始化数据...");
        MessageTemplateService messageTemplateService = SpringContextUtils.getBean(MessageTemplateService.class);
        ConfigureService configureService = SpringContextUtils.getBean(ConfigureService.class);
        RedisService redisService = SpringContextUtils.getBean(RedisService.class);


        /** 缓存系统参数 */
        setWebConfigToRedis(configureService.select(new Configure(t -> t.setStatus(State.YES))), redisService);
        log.info("加载系统参数成功！");

        /** 缓存消息模板 */
        setMessageTempToRedis(messageTemplateService.select(new MessageTemplate()), redisService);
        log.info("加载消息模板成功！");

    }

    private static void setWebConfigToRedis(List<Configure> list, RedisService redisService) {
        // 更新缓存系统参数
        for (Configure config : list) {
            log.debug("缓存参数:key=" + CacheID.CONFIG_PREFIX + config.getNid() + ",val=" + config.getValue());
            redisService.put(CacheID.CONFIG_PREFIX + config.getNid(), config.getValue());
        }
    }

    private static void setMessageTempToRedis(List<MessageTemplate> list, RedisService redisService) {
        // 更新缓存系统参数
        for (MessageTemplate template : list) {
            log.debug("缓存参数:key=" + CacheID.TEMPLATE_MESSAGE_PREFIX + template.getNid() + ",val=" + template);
            redisService.put(CacheID.TEMPLATE_MESSAGE_PREFIX + template.getNid(), template);
        }
    }
}
